import React, { useEffect, useState } from 'react';
import Header from '@/components/Header/Header';
import UploadImage from '@/components/UploadImage/UploadImage';
import Rate from '@/components/Rate/Rate';
import { queryOrderDetail, queryComment } from '@/services/order';
import { AsyncLoading, Message } from '@/design';
import { isEmpty } from '@/utils/common';
import { history } from 'umi';
import styles from './comment.less';

export default function (props: any) {
  let unmount = false;
  const [orderInfo, setOrderInfo] = useState<any>({});
  const [formDt, setFormDt] = useState<any>({
    star: 5
  });
  const { orderId = '' } = props.match.params;
  const userInfo = localStorage.getItem('userInfo');
  const { userId = '' } = JSON.parse(userInfo || '{}');
  useEffect(() => {
    fetchOrderDetail();
    setDefaultFormDt();
    return () => {
      unmount = true;
    }
  }, []);

  useEffect(() => {
    setDefaultFormDt();
  }, [orderInfo]);

  const setDefaultFormDt = () => {
    if (isEmpty(orderInfo)) return;
    let newItemList: any = orderInfo.orderItemList || [];
    newItemList = newItemList.map((item: any) => {
      return {
        productId: item.productId,
        likeStatus: item.likeStatus,
        unlikeContent: item.unlikeContent,
        productName: item.productName,
        orderId,
        orderDetailId: item.detailId,
        goodsPrice: item.productPrice,
        productImage: item.productIcon,
      }
    });
    setFormDt({
      ...formDt,
      productCommentList: newItemList
    });
  }

  const fetchOrderDetail = async () => {
    if (isEmpty(orderId)) {
      return;
    };
    let result = await queryOrderDetail({ id: orderId, isReturnUmeIntegral: '1' });
    if (unmount || !result) return;
    setOrderInfo(result.data);
  }

  const handleChangeProductCommentList = (currnentItem: any, Itemvalue: string, param: string) => {
    let newProductCommentList = formDt.productCommentList;
    newProductCommentList = newProductCommentList.map((item: any) => {
      if (item.orderDetailId === currnentItem.orderDetailId) {
        return {
          ...item,
          [param]: Itemvalue
        }
      }
      return item
    })
    setFormDt({
      ...formDt,
      productCommentList: newProductCommentList
    })
  }

  const handleChangeFormDt = (value:any ,name:string, type?: string) => {
    let newItem: any = {};
    if ((typeof value === 'object' && value.hasOwnProperty('target'))) {
      value = value.target.value.replace(/\s+/g, '');
    }
    newItem[name] =  value;
    setFormDt({
      ...formDt,
      ...newItem
    });
  }

  const handleSumbit = () => {
    const { productCommentList, content, images } = formDt;
    if(isEmpty(images)) {
      return Message.error('請選擇圖片')
    }
    if(isEmpty(content)) {
      return Message.error('請填寫評語')
    }
    fetchComment();
  }

  const fetchComment = async() => {
    const { productCommentList, content, images } = formDt;
    let newProductCommentList = productCommentList.map((item: any)=>{
      let types = new Map([['zan', 1], ['cai', 0]]);
      return {
        ...item,
        likeStatus: types.get(item.likeStatus)
      }
    })
    let result = await queryComment({
      productCommentList: newProductCommentList,
      content,
      images,
      braId: localStorage.getItem('BRAID'),
      sync: 1,
      userId,
      orderId
    });
  if (!result || !result.data) return false;
    Message.success('評論成功')
  }

  const { productCommentList, content, star } = formDt;
  
  return <>
    {isEmpty(orderInfo) && isEmpty(productCommentList) ? <AsyncLoading /> : <div className={styles.comment_wrap}>
      <Header hasBack title={'填寫評論'}></Header>
      <div className={styles.product_info}>
        <h3>菜品評價</h3>
        {(productCommentList || []).map((item: any, index: number) => {
          return <div key={`${item.productId}_${index}`}>
            <div className={styles.product} >
              <span>{item.productName}</span>
              <span>
                <i className={`${styles.like_icon_default} ${item.likeStatus === 'zan' ? styles.actived : ''}`} onClick={() => { handleChangeProductCommentList(item, 'zan', 'likeStatus') }}></i>
                <i className={`${styles.like_icon} ${item.likeStatus === 'cai' ? styles.actived : ''}`} onClick={() => { handleChangeProductCommentList(item, 'cai', 'likeStatus') }}></i>
              </span>
            </div>
            {item.likeStatus === 'cai' &&
              <div className={styles.input_wrap}>
                <textarea
                  className={styles.input}
                  maxLength={100}
                  rows={3}
                  placeholder='非常抱歉，我们做得还不够好，请告诉我们，我们会改善的噢~'
                  onChange={(e: any) => { handleChangeProductCommentList(item, e.target.value, 'unlikeContent') }}
                ></textarea>
                <span className={styles.input_num}><i>{100 - (isEmpty(item.unlikeContent) ? 0 : item.unlikeContent.length)}</i>/100</span>
              </div>}
          </div>
        })}
      </div>
      <div className={styles.picture_wrap}>
        <h3>曬單</h3>
        <div className={styles.uplaod_wrap}>
          <UploadImage className={styles.upload} onChange={(e: any) => { handleChangeFormDt(e, 'images', 'pic') }} />
        </div>
        <h3>訂單評價：<Rate num={star} canUse onChange={(e: any) => { handleChangeFormDt(e, 'star') }}/> </h3>
        <div className={styles.input_wrap}>
            <textarea
              className={styles.input}
              maxLength={140}
              rows={3}
              placeholder='非常抱歉，我们做得还不够好，请告诉我们，我们会改善的噢~'
              onChange={(e: any) => { handleChangeFormDt(e.target.value, 'content') }}
            ></textarea>
            <span className={styles.input_num}><i>{140 - (isEmpty(content) ? 0 : content.length)}</i>/140</span>

        </div>
      </div>
      <div className={styles.form_btn}>
        <button className={styles.form_submit} type="button" onClick={handleSumbit}>
          提交
        </button>
      </div>
    </div>}

  </>

}